package com.woniuxy.company5.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.company5.util.JwtUtils;
import com.woniuxy.company5.util.RedisCache;
import com.woniuxy.company5.util.Result;
import com.woniuxy.company5.vo.UserPermissionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author ：fengSir
 * @date ：Created By 2022-12-01 15:27
 * @description ：TODO
 */
public class LoginAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private RedisCache redisCache;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.out.println("成功");
        SecurityContextHolder.getContext().setAuthentication(authentication);//采用threadLocal模型
        LoginUser user = (LoginUser) authentication.getPrincipal();
        //登录成功存储当前用户的权限等信息
       redisCache.setCacheObject("rbac:"+user.getUsername(),user,7, TimeUnit.DAYS);
        List<UserPermissionVo> menuList = user.getMenuList();
        String token = jwtUtils.generateToken(user.getUsername());
        response.setContentType("application/json;charset=utf-8");
        String string = new ObjectMapper().writeValueAsString(Result.ok().data("menuList",menuList).data("token",token).data("userdata",user.getUser()));
        response.getWriter().println(string);
    }
}
